/*
 *  微信： tornodo
 *  博客：https://www.jianshu.com/u/1b05a5363c32
 *  微信公众号： 工匠前沿
 */

require('pixi.js');
require('phaser');

let WIDTH = 800;
let HEIGHT = 600;
let score = 0; //得分
let changeScore = 10;//切换背景得分
let changeBGScore= 0;//统计累计等分更换背景，然后置0重新统计
let scoreText;//得分的文字说明，添加到舞台上
let topScore = 0;//最高得分
let distance = 180;//上下烟囱之间的距离
let MaxChinmeyNum = 5;//每次游戏开始默认生成10个烟囱，上下各5个
let ChimneyGroupsUp;//上面的烟囱组
let ChimneyGroupsDown;//下面的烟囱组
let minChimneyHeight = 120; // 烟囱在场景上最小的一个Y值
let maxChimneyHeight = 300; // 烟囱在场景上最大的一个Y值
let birdDropSpeed = 1200;
let speed = -280;//烟囱移动速度
let day = '#6ec5ce';
let night = '#0493a2';

export class BootScene extends Phaser.State {
    preload() {
        this.load.image('loading', 'assets/image/progress.png');
    }

    create() {
        this.state.start('preloader');
    }
}

export class PreloadScene extends Phaser.State {
    preload() {
        const loadingSprite = this.add.sprite((this.world.width - 311) / 2, this.world.height / 2, 'loading');
        this.load.setPreloadSprite(loadingSprite, 0);
        this.load.image('bg', 'assets/image/bg.png');
        this.load.atlasJSONHash('ui', 'assets/image/ui.png', 'assets/image/ui');
        this.load.audio('die', 'assets/audio/die.wav');
        this.load.audio('music', 'assets/audio/bg.mp3');
    }

    create() {
        this.state.start('menu');
    }
}

export class MenuScene extends Phaser.State {
    create() {
        this.bg = this.add.sprite(0, 0, 'bg');
        this.bird = this.add.sprite(0, 0, 'ui', 'bird1.png');
        this.bird.anchor.set(0.5);
        this.bird.x = this.game.world.centerX;
        this.bird.y = this.game.world.centerY - 100;
        this.bird.animations.add('bird_fly', ['bird1.png', 'bird2.png', 'bird3.png'], 20, true, false);
        this.bird.animations.play('bird_fly');
        this.startButton = this.add.sprite(0, 0, 'ui', 'button.png');
		this.startButton.anchor.set(0.5);
		this.startButton.x = this.game.world.centerX;
		this.startButton.y = this.bird.y + this.bird.height + this.startButton.height / 2;
		this.startButton.inputEnabled = true;
		this.startButton.input.useHandCursor = true;
		this.startButton.events.onInputDown.add(this.startGame, this);
    }

    startGame() {
    	this.bg.destroy();
    	this.bird.destroy();
    	this.startButton.destroy();
        this.state.start('startGame');
    }
}

export class StartScene extends Phaser.State {
    preload() {
        this.game.stage.backgroundColor = day;//设置背景色为白天
        this.cloud1 = this.add.tileSprite(0, this.game.height - 68 * 2, this.game.width, 95, 'ui', 'cloud1.png');
        this.cloud1.autoScroll(speed / 10, 0);//自动重复滚动
        this.cloud2 = this.add.tileSprite(0, this.game.height - 68 * 2, this.game.width, 95, 'ui', 'cloud2.png');
        this.cloud2.autoScroll(speed / 10, 0);//自动重复滚动
        this.cloud2.visible = false;//隐藏
        this.building1 = this.add.tileSprite(0, this.game.height - 68, this.game.width, 68, 'ui', 'building1.png');
        this.building1.autoScroll(speed / 5, 0);//自动重复滚动
        this.building2 = this.add.tileSprite(0, this.game.height - 68, this.game.width, 68, 'ui', 'building2.png');
        this.building2.autoScroll(speed / 5, 0);//自动重复滚动
        this.building2.visible = false;//隐藏
        this.bang = this.add.audio('die');
        this.music = this.add.audio('music');
        this.input.maxPointers = 1;
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        ///初始化状态
        score = 0;
        changeBGScore = 0;
    }

    create() {
        this.music.play('', 0, 1, true);
        this.bird = this.add.sprite(0, 300, 'ui', 'bird1.png');
        this.game.physics.arcade.enable(this.bird);
        this.bird.anchor.set(0.5);
        this.bird.x = this.game.world.centerX;
        this.bird.y = this.game.world.centerY;
        this.bird.animations.add('bird_fly', ['bird1.png', 'bird2.png', 'bird3.png'], 20, true, false);
        this.bird.animations.play('bird_fly');
        this.bird.body.gravity.y = birdDropSpeed;
    	ChimneyGroupsUp = this.game.add.group();//上面的烟囱组
    	ChimneyGroupsDown = this.game.add.group();
    	this.initChimney();
        topScore = localStorage.getItem("bird_topScore") === null ? 0 : localStorage.getItem("bird_topScore");
        scoreText = this.game.add.text(10, 10, "-", {
            font:"bold 18px Arial",
            fill: "#ffffff"
        });
        this.game.input.onDown.add(this.fly, this); //给鼠标按下事件绑定鸟的飞翔动作
        updateScore();
        this.moveAChimney();
        ChimneyGroupsUp.forEach(function(Chimney) {
        	this.game.physics.arcade.collide(this.bird, Chimney);//烟囱头
        	Chimney.children.forEach(function(item) {//烟囱体
        		this.game.physics.arcade.collide(this.bird, item);
        	}, this);
        }, this);
        ChimneyGroupsDown.forEach(function(Chimney) {
        	this.game.physics.arcade.collide(this.bird, Chimney);//烟囱头
        	Chimney.children.forEach(function(item) {//烟囱体
        		this.game.physics.arcade.collide(this.bird, item);
        	}, this);
        }, this);
		this.game.time.events.loop(1500, this.moveAChimney, this); //利用时钟事件来循环产生管道
    }

    update() {
        if(this.bird.x <= 0 || this.bird.x >= this.game.width || this.bird.y <= 0 || this.bird.y >= this.game.height) {
    		this.gameOver();
    	}//小鸟飞出或是跌落出舞台
        ChimneyGroupsUp.forEach(function(Chimney) {
        	if (Chimney.x + Chimney.width / 2 < this.bird.x + this.bird.width / 2 && Chimney.scored === false) {
        		Chimney.scored = true;
        		score += 1;
        		changeBGScore += 1;
        		updateScore();
        	}//如果小鸟飞过了烟囱，加一分
        	this.game.physics.arcade.overlap(this.bird, Chimney, this.gameOver, null, this);
        	Chimney.children.forEach(function(item) {
        		this.game.physics.arcade.overlap(this.bird, item, this.gameOver, null, this);
        	}, this);//如果小鸟跟烟囱或是烟囱体有碰撞直接结束游戏
        }, this);
        ChimneyGroupsDown.forEach(function(Chimney) {
        	this.game.physics.arcade.overlap(this.bird, Chimney, this.gameOver, null, this);
        	Chimney.children.forEach(function(item) {
        		this.game.physics.arcade.overlap(this.bird, item, this.gameOver, null, this);
        	}, this);
        }, this);
    	if(this.bird.angle < 90) {
    		this.bird.angle += 2.5;//一直朝下旋转鸟头
    	}
    	if (changeBGScore === changeScore) {//看看是否该切换背景了
			changeBGScore = 0;//清空统计
			if(this.cloud2.visible === false) {//切换到黑夜
				this.cloud2.visible = true;
				this.building2.visible = true;
				this.cloud1.visible = false;
				this.building1.visible = false;
				this.game.stage.backgroundColor = night;
			} else {//切换到白天
				this.cloud2.visible = false;
				this.building2.visible = false;
				this.cloud1.visible = true;
				this.building1.visible = true;
				this.game.stage.backgroundColor = day;
			}
		}
    }

    fly() {
		this.bird.body.velocity.y = -350; //给鸟设一个向上的速度
    	this.game.add.tween(this.bird).to({angle:-30}, 100, null, true, 0, 0, false); //上升时头朝上的动画
    }

    gameOver() {
		this.bang.play();
	    this.clearChimney();//清空保存的烟囱数组
	    localStorage.setItem("bird_topScore", Math.max(score, topScore));
	    updateScore();
	    this.music.stop();
	    this.cloud1.destroy();
	    this.cloud2.destroy();
	    this.building1.destroy();
	    this.building2.destroy();
	    this.bird.destroy();
	    this.bang.destroy();
	    this.music.destroy();
	    this.state.start('stopGame');
    }

	//移动一个烟囱
	moveAChimney() {
		var up = ChimneyGroupsUp.getFirstDead();
		if (up == null) {
			return;
		}
		var y = this.game.rnd.between(minChimneyHeight, maxChimneyHeight);
		up.reset(this.game.width, y)
		up.scored = false;
		up.body.velocity.x = speed;
		var down = ChimneyGroupsDown.getFirstDead();
		if (down != null) {
			down.angle = 0;
			down.reset(this.game.width, y + distance);
			down.body.velocity.x = speed;
		}
	}

	// 每次游戏重新开始的时候，清空保存的烟囱数组
	clearChimney() {
		console.log("清理所有烟囱");
		ChimneyGroupsUp.forEach(function(Chimney) {
			Chimney.destroy();
		});
		ChimneyGroupsUp.destroy();
		ChimneyGroupsDown.forEach(function(Chimney) {
			Chimney.destroy();
		});
		ChimneyGroupsDown.destroy();
	}

	// 随机10个烟囱
	initChimney() {
		this.initUpChimney();
		this.initDownChimney();
		ChimneyGroupsUp.setAll('checkWorldBounds',true); //边界检测
		ChimneyGroupsUp.setAll('outOfBoundsKill',true); //出边界后自动kill
		ChimneyGroupsDown.setAll('checkWorldBounds',true); //边界检测
		ChimneyGroupsDown.setAll('outOfBoundsKill',true); //出边界后自动kill
	}

	initUpChimney() {
		for(var i = 0;i < MaxChinmeyNum;i++) {
			var chimney = this.game.add.sprite(this.game.width, this.game.height, 'ui', '6.png');
			chimney.scored = false;
			chimney.anchor.set(0.5);
			chimney.angle = 180;//角度转动180°
			this.game.physics.arcade.enable(chimney);
			var halfH = chimney.height / 2;
			var body = this.game.add.sprite(0, 0, 'ui', '9.png');
			body.anchor.set(0.5, 1.5);
			body.angle = 180;//角度转动180°
			this.game.physics.arcade.enable(body);
			chimney.addChild(body);
			var n = Math.floor((this.game.height - halfH) / body.height);
			for (var j = 0;j < n;j++) {
				var b = this.game.add.sprite(0, 0, 'ui', '9.png');
				b.anchor.set(0.5, 1.5 + (j + 1));
				b.angle = 180;//角度转动180°
				chimney.addChild(b);
				this.game.physics.arcade.enable(b);
			}
			chimney.alive = false;
			chimney.visible = false;
			ChimneyGroupsUp.add(chimney);
		}
	}

	initDownChimney() {
		for(var i = 0;i < MaxChinmeyNum;i++) {
			var chimney = this.game.add.sprite(this.game.width, 0, 'ui', '6.png');
			chimney.anchor.set(0.5);//烟囱头的锚点设为中心点
			this.game.physics.arcade.enable(chimney);//对烟囱头启动物理引擎
			var halfH = chimney.height / 2;//烟囱头高度的一半
			var body = this.game.add.sprite(0, 0, 'ui', '9.png');//烟囱体
			body.anchor.set(0.5, -0.5);//同样设置锚点，相对与烟囱头的锚点
			this.game.physics.arcade.enable(body);//启动物理引擎
			chimney.addChild(body);
			var n = Math.floor((this.game.height - halfH) / body.height);//计算还需要多少烟囱体
			for (var j = 0;j < n;j++) {
				var b = this.game.add.sprite(0, 0, 'ui', '9.png');
				b.anchor.set(0.5, -0.5 - (j + 1));
				chimney.addChild(b);
				this.game.physics.arcade.enable(b);
			}
			chimney.alive = false;
			chimney.visible = false;
			ChimneyGroupsDown.add(chimney);
		}
	}
}

export class StopScene extends Phaser.State {
    preload() {
		this.game.stage.backgroundColor = day;
        this.bird = this.add.sprite(0, 0, 'ui', 'bird1.png');
        this.bird.anchor.set(0.5);
        this.bird.x = this.game.world.centerX;
        this.bird.y = this.game.world.centerY - 100;
        this.bird.animations.add('bird_fly', ['bird1.png', 'bird2.png', 'bird3.png'], 20, true, false);
        this.bird.animations.play('bird_fly');
        this.startButton = this.add.sprite(0, 0, 'ui', 'button.png');
		this.startButton.anchor.set(0.5);
		this.startButton.x = this.game.world.centerX;
		this.startButton.y = this.bird.y + this.bird.height + this.startButton.height / 2;
		this.startButton.inputEnabled = true;
		this.startButton.input.useHandCursor = true;
		this.startButton.events.onInputDown.add(this.startGame, this);
        scoreText = this.game.add.text(0, this.bird.y - this.bird.height - 30, "-", {
            font:"bold 28px Arial",
            fill: "#FFFFFF"
        });
        scoreText.anchor.set(0.5);
        scoreText.x = this.bird.x;
    }

    create() {
        updateScore();
    }

    startGame() {
    	this.bird.destroy();
    	this.startButton.destroy();
    	scoreText.destroy();
        this.state.start('startGame');
    }
}

function updateScore() {
    scoreText.text = "得分：" + score + "    最高得分：" + Math.max(score, topScore);
}